package com.jsoft.jsofted.platform.service.impl;

import com.jsoft.jsofted.platform.entity.TenantEntity;
import com.jsoft.jsofted.platform.mapper.TenantMapper;
import com.jsoft.jsofted.framework.mybatis.CocQueryWrapper;
import com.jsoft.jsofted.framework.service.impl.CocServiceImpl;
import com.jsoft.jsofted.platform.service.TenantService;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Service
public class TenantServiceImpl extends CocServiceImpl<TenantMapper, TenantEntity> implements TenantService {

    @Override
    public TenantEntity getForLogin(String tenantId, String username, String password) {
        return this.baseMapper.getForLogin(tenantId, username, password);
    }

    protected CocQueryWrapper parseQueryWrapper(Map queryParams) {
        if (queryParams == null) {
            queryParams = new LinkedHashMap();
        }

        CocQueryWrapper queryWrapper = new CocQueryWrapper();

        this.parseSortParams(queryWrapper, queryParams);
        this._parseKeywordsParams(queryWrapper, queryParams);
        this._parseStatusParams(queryWrapper, queryParams);
        this._parseCreatedDateParams(queryWrapper, queryParams);

        return queryWrapper;
    }

    /**
     * 解析【条件参数】中的【创建时间参数】
     */
    private void _parseCreatedDateParams(CocQueryWrapper queryWrapper, Map condParams) {
        List createTimes = (List) condParams.get("createTimes");
        if (createTimes != null && createTimes.size() == 2) {
            queryWrapper.ge("create_time", createTimes.get(0));
            queryWrapper.le("create_time", createTimes.get(1) + " 23:59:59");
        }
    }

    /**
     * 解析【条件参数】中的【关键字参数】
     */
    private void _parseKeywordsParams(CocQueryWrapper queryWrapper, Map condParams) {
        String keywords = (String) condParams.get("keywords");
        if (keywords == null || keywords.trim().length() == 0) {
            return;
        }

        Consumer<CocQueryWrapper> consumer = qw -> {
            qw.like("name", keywords);
            qw.or();
            qw.like("contact_user", keywords);
            qw.or();
            qw.like("contact_tel", keywords);
            qw.or();
            qw.like("address", keywords);
            qw.or();
            qw.like("system_name", keywords);
        };
        queryWrapper.and(consumer);
    }

    /**
     * 解析【条件参数】中的【状态参数】
     */
    private void _parseStatusParams(CocQueryWrapper queryWrapper, Map condParams) {
        String statusCode = (String) condParams.get("statusCode");
        if (statusCode != null && statusCode.trim().length() > 0) {
            queryWrapper.eq("status_code", statusCode);
        }
    }
}
